package com.tiennt.android.callnotes.models;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;

import com.tiennt.android.callnotes.PopupNotesActivity;
import com.tiennt.android.callnotes.db.DbAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

public class IncomingReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(final Context context, Intent intent) {
		// TODO Auto-generated method stub
		final Bundle extras = intent.getExtras();
		if (extras != null) {
			String state = extras.getString(TelephonyManager.EXTRA_STATE);
			if (state != null) {
				if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
					new Handler().postDelayed(new Runnable() {
						public void run() {
							Bundle data = new Bundle();
							String contactId = "";
							String number = extras
									.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

							Uri contackLookup = Uri
									.withAppendedPath(
											ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
											Uri.encode(number));

							Cursor cursor = context
									.getContentResolver()
									.query(contackLookup,
											new String[] { ContactsContract.PhoneLookup._ID, },
											null, null, null);

							if (cursor != null) {
								if (cursor.moveToFirst()) {
									contactId = cursor
											.getString(cursor
													.getColumnIndex(ContactsContract.PhoneLookup._ID));

									data.putString(
											ProjectUtils.BUNDLEKEY_CONTACTID,
											contactId);
									data.putInt(
											ProjectUtils.BUNDLEKEY_CALLTYPE,
											ProjectUtils.CALLTYPE_INCOMING);
								}
								cursor.close();
							}

							DbAdapter adapter = new DbAdapter(context);
							adapter.open();
							if (adapter.getCount(contactId,
									ProjectUtils.CALLTYPE_INCOMING) != 0) {
								Intent intentPhoneCall = new Intent(context,
										PopupNotesActivity.class);
								intentPhoneCall.putExtras(data);
								intentPhoneCall
										.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								intentPhoneCall
										.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
								intentPhoneCall
										.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

								context.startActivity(intentPhoneCall);
							}
							adapter.close();
						}
					}, 1000);
				}
			}

		}
	}
}
